package com.teamin.service.impl;

import com.mysql.cj.core.util.StringUtils;
import com.teamin.config.ErrorCode;
import com.teamin.entity.*;
import com.teamin.mapper.CircleMapper;
import com.teamin.mapper.NetDiskMapper;
import com.teamin.service.*;
import com.teamin.vo.CircleVO;
import com.teamin.web.exception.GlobalErrorInfoException;
import com.teamin.web.model.ErrorInfo;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CircleServiceImpl implements CircleService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private CircleMapper circleMapper;
	@Autowired
	private NameRuleService nameRuleService;

	@Autowired
	private CircleService circleService;

	@Autowired
	private UserService userService;

	@Autowired
	private WebsocketService websocketService ;

	@Autowired
	private LogServiceImpl logService ; //日志服务

	@Autowired
	private WxGroupService wxGroupService;

	@Autowired
	NetDiskMapper netDiskMapper;

	/**
	 * 新增圈子
	 * @param record
	 * @return 圈子ID
	 * @throws GlobalErrorInfoException
	 */
	@Override
	public long insertCircle(CircleEntity record) throws GlobalErrorInfoException {
		try {
			int result = circleMapper.insertSelective(record);
			if (result == 0) {
				// 创建失败异常
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.CREATE_CIRCLE_FAIL));
			}
			/*创建圈子后，创建网盘默认文件夹*/
			NetDisk netDisk = new NetDisk();
			netDisk.setCreateUserid(record.getCreaterId());

			netDisk.setCircleid(Integer.valueOf(record.getCircleId() + ""));
			netDisk.setFileName("图片");
			netDiskMapper.save(netDisk);
			netDisk.setCircleid(Integer.valueOf(record.getCircleId() + ""));
			netDisk.setFileName("视频");
			netDiskMapper.save(netDisk);
			netDisk.setCircleid(Integer.valueOf(record.getCircleId() + ""));
			netDisk.setFileName("文档");
			netDiskMapper.save(netDisk);
			return record.getCircleId();
			
		} catch (Exception e) {
			// 创建失败异常
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.CREATE_CIRCLE_FAIL));
		}
	}

	@Override
	public CircleEntity selectCircleById(Long circleId,Long userId) throws GlobalErrorInfoException {
		try {
			CircleEntity circleEntity = circleMapper.selectByPrimaryKey(circleId,userId);
			if (circleEntity == null) {
				// 没有找到异常
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.NOT_FOUND, ErrorCode.FIND_CIRCLE_NULL));
			}
			return circleEntity;
		} catch (Exception e) {
			// 查询失败
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.FIND_CIRCLE_FAIL));
		}
	}

	@Override
	public CircleEntity selectCircleWithUsersById(Long id,Long userId) throws GlobalErrorInfoException {
		try {
			CircleEntity circleEntity = circleMapper.selectWithUsersByPrimaryKey(id,userId);
			if (circleEntity == null) {
				// 没有找到异常
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.NOT_FOUND, ErrorCode.FIND_CIRCLE_NULL));
			}
			return circleEntity;
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			// 查询失败
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.FIND_CIRCLE_FAIL));
		}
	}

	@Override
	public int updateCircle(CircleEntity record,boolean check,Long contolUser) throws GlobalErrorInfoException {
		//if(check && record.getCircleName() != null)
		//	nameRuleService.cricleNameRule(record.getCircleName());

		CircleEntity oldCircle = null  ;
		try {
			oldCircle = selectCircleById(record.getCircleId(), contolUser);;
		}catch(Exception e) {

		}


		int result = circleMapper.updateByPrimaryKeySelective(record);

		//增加日志
		addUpdateCircleLog(record,contolUser,oldCircle);

		if (result == 0) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.UPDATE_CIRCLE_FAIL));
		}
		return result;
	}

	public void addUpdateCircleLog(CircleEntity record,Long controlUser,CircleEntity old) {

		if(old== null) {
			return ;
		}

		String controlUserName = getUserName(record.getCircleId(), controlUser);

		//修改工作圈名称
		if(!StringUtils.isNullOrEmpty(record.getCircleName()) && !record.getCircleName().equals(old.getCircleName())) {
			logService.insertCircleLog(record.getCircleId(), LogService.HANDLE.MODIFY, LogService.CircleHandleField.CIRCLE_NAME,controlUser,controlUserName,record.getCircleName()) ;
		}

		//圈子分享
		if(record.getCanMemberShare() != null) {
			if(record.getCanMemberShare()) { //打开圈子分享
				logService.insertCircleLog(record.getCircleId(), LogService.HANDLE.OPEN, LogService.CircleHandleField.CIRCLE_SHARE,controlUser,controlUserName,null) ;
			}else {
					logService.insertCircleLog(record.getCircleId(), LogService.HANDLE.CLOSE, LogService.CircleHandleField.CIRCLE_SHARE,controlUser,controlUserName,null) ;
			}
		}

		//圈子邀请
		if(record.getCanMemberInvite() != null) {
			if(record.getCanMemberInvite()) { //打开圈子邀请
				logService.insertCircleLog(record.getCircleId(), LogService.HANDLE.OPEN, LogService.CircleHandleField.CIRCLE_INVITE,controlUser,controlUserName,null) ;
			}else {
				logService.insertCircleLog(record.getCircleId(), LogService.HANDLE.CLOSE, LogService.CircleHandleField.CIRCLE_INVITE,controlUser,controlUserName,null) ;
			}
		}

		//圈子权限
		if(record.getOpenGroupCircleCheck() != null) {
			if(record.getOpenGroupCircleCheck() == 1) { //打开圈子权限
				logService.insertCircleLog(record.getCircleId(), LogService.HANDLE.OPEN, LogService.CircleHandleField.CIRCLE_AUTHORITY_CHECK,controlUser,controlUserName,null) ;
			}else {
				logService.insertCircleLog(record.getCircleId(), LogService.HANDLE.CLOSE, LogService.CircleHandleField.CIRCLE_AUTHORITY_CHECK,controlUser,controlUserName,null) ;
			}
		}
	}

	@Override
	public int addMemberToCircle(long circleId, long userId) throws GlobalErrorInfoException {
		try {
			if(userService.userInCircle(userId, circleId)) {
				return 1 ;
			}
			int result = circleMapper.addMemberToCircle(circleId, userId);
			if (result == 0) {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.ADD_USER_TO_CIRCLE_FAIL));
			}
			return result;
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.ADD_USER_TO_CIRCLE_FAIL));
		}
	}

	@Override
	public int removeMemberFromCircle(long circleId, long userId,Long controlUser,String userFlag) throws GlobalErrorInfoException {
		try {

			CircleUserEntity userEntity = circleService.selectMemberCircle(circleId, userId);
			CircleEntity circle = circleService.selectCircleById(circleId, userId);
			CircleUserEntity controlUserEntity = circleService.selectMemberCircle(circleId, controlUser);
			int re  = 0 ;
			// 如果是创建者或者要移除的用户是当前登录用户,
			if (userEntity != null) {
				re = circleMapper.removeMemberToCircle(circleId, userId);
				//删除成员
				logService.insertCircleLog(circleId, LogService.HANDLE.DELETE, (userId==controlUser?LogService.CircleHandleField.CIRCLE_MEMBER_MYSELF:LogService.CircleHandleField.CIRCLE_MEMBER),controlUser,(circle.getCreaterId()==controlUser?"管理员":"")+getUserName(circleId,controlUser),getUserName(circleId,userId)) ;
			}

			//如果是创建者并且移除的是自已则将成员中最先添加的用户设为创建者
			if(re != 0 && circle.getCreaterId().equals(userId)){
				Long firstUserId = circleService.getFirstUserId(circleId) ;
				if(firstUserId != null && firstUserId !=0 ) {
					CircleEntity circleEntity = new CircleEntity() ;
					circleEntity.setCreaterId(firstUserId);
					circleEntity.setCircleId(circleId);
					circleService.updateCircle(circleEntity,false,controlUser) ;
					logService.insertCircleLog(circleId, LogService.HANDLE.MODIFY, (userId==controlUser?LogService.CircleHandleField.CIRCLE_CREATER:LogService.CircleHandleField.CIRCLE_MEMBER),0L,"系统",getUserName(circleId,firstUserId)) ;
				}
			}

			//发送socket通知
			websocketService.sendCircle(controlUserEntity,circleId, WebsocketService.CirclePropertise.USER, WebsocketService.Control.DELETE,userId,userFlag);
			websocketService.sendToUserNotifi(userId,controlUserEntity,circleId,WebsocketService.NotifiPropertise.REMOVED_USER_CIRCLE,userEntity,userFlag);
			websocketService.sendToCircleUserNotifi(userId,controlUserEntity,circleId,WebsocketService.NotifiPropertise.REMOVED_USER_CIRCLE,null,userFlag);

		} catch (Exception e) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.REMOVE_USER_FROM_CIRCLE_FAIL));
		}
		return 1;
	}

	@Override
	public int removeMembersFromCircle(long circleId, String[] userId,Long controlUser,String userFlag) throws GlobalErrorInfoException {
		for(int i = 0 ; i < userId.length ; i ++) {
			removeMemberFromCircle(circleId,Long.parseLong(userId[i]),controlUser,userFlag) ;
		}
		return 1 ;
	}

	@Override
	public List<CircleUserEntity> selectMemberToCircle(Long circleId,List<Long> userIds) {
		return circleMapper.selectMemberToCircle(circleId,userIds);
	}

	@Override
	public CircleUserEntity selectMemberFromCircle(Long circleId, Long userId) {
		return circleMapper.selectMemberFromCircle(circleId,userId);
	}

	@Override
	public List<CircleEntity> selectCircleByUser(long userId) {
		return circleMapper.selectCircleByUser(userId);
	}

	@Override
	public List<CircleEntity> selectCircleAndUser(long userId) throws GlobalErrorInfoException {
		return circleMapper.selectCircleAndUser(userId);
	}

	/**
	 * 查询用户所在的圈子列表 包含用户最后一条围度消息
	 */
	@Override
	public List<CircleVO> selectUserCircleV012(Long userId,Long circleId){
		return circleMapper.selectUserCircleV012(userId,circleId) ;
	}

	/**
	 * 查询用户所在的圈子列表 包含用户最后一条围度消息
	 */
	@Override
	public CircleVO selectCircleV012(long userId,long circleId){
		List<CircleVO> res = circleMapper.selectUserCircleV012(userId,circleId) ;
		if(res==null || res.size() ==0 ) {
			return null ;
		}else {
			return res.get(0);
		}
	}

	@Override
	public CircleEntity addCircleEntity(CircleEntity circleEntity, Long userId) throws GlobalErrorInfoException {
		//nameRuleService.cricleNameRule(circleEntity.getCircleName());
		circleEntity.setCreaterId(userId);
		long id = insertCircle(circleEntity);
		addMemberToCircle(id, userId);
		circleEntity = selectCircleWithUsersById(id,userId);

		// 添加圈子日志
		logService.insertCircleLog(circleEntity.getCircleId(), LogService.HANDLE.ADD, LogService.CircleHandleField.CIRCLE,userId,getUserName(circleEntity.getCircleId(),userId),circleEntity.getCircleName()) ;
		return circleEntity;
	}

	@Override
	public int deleteCircleById(Long id) throws GlobalErrorInfoException {
		try {
			int result = circleMapper.deleteCircleById(id);
			if (result == 0) {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.DELETE_CIRCLE_FAIL));
			}

			return result;
		} catch (Exception e) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.DELETE_CIRCLE_FAIL));
		}
	}

	public boolean circleExist(Long circleId) {
		return circleMapper.circleExist(circleId);
	}
	
	@Override
	public CircleUserEntity selectMemberCircle(Long circleId,Long userId) throws GlobalErrorInfoException {
		try {
			CircleUserEntity userEntity = circleMapper.selectMemberFromCircle(circleId, userId);
			if (userEntity == null) {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_USER_FROM_CIRCLE_NULL));
			}
			return userEntity;
		} catch (Exception e) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_USER_FROM_CIRCLE_NULL));
		}
	}

	@Override
	public List<NotifiEntity> selectNotifiMember(Long circleId, List<Long> userIds) {
		return circleMapper.selectNotifiMember(circleId,userIds);
	}

	/**
	 * 获取圈子中第一个加入的成员ID
	 * @param circleId 圈子ID
	 * @return 成员ID
	 */
	public Long getFirstUserId(@Param("circleId") Long circleId){
		return circleMapper.getFirstUserId(circleId) ;
	}


	/**
	 * 判断用户是不是圈子的创建者
	 * @param circleId 圈子ID
	 * @param userId 用户ID
	 * @return
	 */
	@Override
	public boolean isCreater(Long circleId, Long userId){
		return circleMapper.isCreater(circleId,userId) ;
	}


	@Override
	public boolean updateUser(Long circleId, Long userId,String nickName,String circlePhone,String circleEmail,String circleJob,Long controlUser,boolean isCreater){

		String oldName = getUserName(circleId, userId);;
		String controlUserName = getUserName(circleId, controlUser);;
		if(circleMapper.existUserInfo(circleId,userId)) {
			circleMapper.updateUserInfo(circleId,userId,nickName,circlePhone,circleEmail,circleJob) ;
		}else {
			circleMapper.insertUserInfo(circleId,userId,nickName,circlePhone,circleEmail,circleJob) ;
		}

		if(!StringUtils.isNullOrEmpty(nickName)) {//修改工作圈成员名称
			logService.insertCircleLog(circleId, LogService.HANDLE.MODIFY, LogService.CircleHandleField.CIRCLE_USER_NICKNAME,controlUser,(isCreater? "管理员 ":"")+controlUserName,nickName,oldName) ;
		}

		return circleMapper.isCreater(circleId,userId) ;
	}

	/**
	 * 根据任务查询圈子的信息
	 * @param taskId circle id
	 * @param userId task id
	 * @return 成员ID
	 */
	@Override
	public CircleEntity selectCircleByTask(Long taskId, Long userId) {
		return circleMapper.selectCircleByTask(taskId,userId) ;
	}

	/**
	 * 圈子的成员数量
	 * @param circleId 圈子ID
	 * @return 成员ID
	 */
	@Override
	public Long selectMemberCount(Long circleId) {
		return circleMapper.selectMemberCount(circleId) ;
	}

	/**
	 * 获取圈子的名称
	 * @param circleId
	 * @return
	 */
	@Override
	public String selectCircleName(Long circleId) {
		return circleMapper.selectCircleName(circleId) ;
	}

	/**
	 * 圈子置顶
	 * @param circleId
	 * @param userId
	 * @param stick 1表示置顶,其他表示取消置顶
	 */
	@Override
	public int stickCircle(Long circleId, Long userId, Integer stick){
		return circleMapper.stickCircle(circleId,userId,stick);
	}

	/**
	 * 获取用户在圈子中的nickname
	 * @param circleId
	 * @param userId
	 */
	@Override
	public String getUserName(Long circleId, Long userId) {
		return circleMapper.getNickName(circleId,userId) ;
	}

	/**
	 * 将用户添加到圈子中
	 * @param circle
	 * @param circleId
	 * @param loginUserId
	 * @param json
	 * @param groupId
	 * @return
	 * @throws GlobalErrorInfoException
	 */
	@Override
	public CircleEntity addUserToCircle(CircleEntity circle, Long circleId, Long loginUserId, ShareInvite json, String groupId,String userFlag) throws GlobalErrorInfoException {
		boolean inCircle1 = userService.userInCircle(loginUserId, circleId);
		if(!inCircle1) {
			if (ShareInvite.CONTROL_SHARE_CIRCLE.equals(json.getControlType()) && circle.getUserCanMemberShare()) {

				if(!inCircle1){
					if(circle!= null && circle.getCreaterId().equals(json.getControlUser()) ) {
						//如果圈子的权限打开了
						if(circle.getOpenGroupCircleCheck() == 1) {
							if(StringUtils.isNullOrEmpty(groupId) || !wxGroupService.existGroupCircle(groupId,circleId)) {
								throw new GlobalErrorInfoException(
										new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.PERMISSION_GROUPID_CIRCLE_USER));
							}
						}
						circleService.addMemberToCircle(json.getControlId(),loginUserId) ;
						//修改工作圈成员名称
						logService.insertCircleLog(circleId, LogService.HANDLE.INVITE, LogService.CircleHandleField.CIRCLE_MEMBER,json.getControlUser(),getUserName(circleId,json.getControlUser()),getUserName(circleId,loginUserId)) ;
						//发送socket通知
						websocketService.sendCircle(loginUserId,circleId, WebsocketService.CirclePropertise.USER, WebsocketService.Control.ADD,loginUserId,userFlag);
					}
				}
			} else if (ShareInvite.CONTROL_INVITE_CIRCLE.equals(json.getControlType()) && circle.getUserCanMemberInvite()) {

				if(!inCircle1){
					//如果圈子的权限打开了
					if(circle.getOpenGroupCircleCheck() == 1) {
						if(StringUtils.isNullOrEmpty(groupId) || !wxGroupService.existGroupCircle(groupId,circleId)) {
							throw new GlobalErrorInfoException(
									new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.PERMISSION_GROUPID_CIRCLE_USER));
						}
					}
					circleService.addMemberToCircle(json.getControlId(),loginUserId) ;

					//修改工作圈成员名称
					logService.insertCircleLog(circleId, LogService.HANDLE.INVITE, LogService.CircleHandleField.CIRCLE_MEMBER,json.getControlUser(),getUserName(circleId,json.getControlUser()),getUserName(circleId,loginUserId)) ;
					//发送socket通知
					websocketService.sendCircle(loginUserId,circleId, WebsocketService.CirclePropertise.USER, WebsocketService.Control.ADD,loginUserId,userFlag);
				}
			}else {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CIRCLE_ERROR_TYPE));
			}
		}

		//是分享圈子 并且有权限分享圈子则 返回圈子信息

		boolean inCircle = userService.userInCircle(loginUserId, circleId);
		// 不属于圈子
		if (!inCircle) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
		}
		return circleService.selectCircleWithUsersById(json.getControlId(),loginUserId);
	}

	/**
	 * 查询圈子的ID
	 * @param taskId
	 * @return
	 */
	@Override
	public Long selectOnlyCircleIdByTask(Long taskId){
		return circleMapper.selectOnlyCircleIdByTask(taskId) ;
	}

	/**
	 * 判断任务是否属于圈子
	 * @param circleId
	 * @return
	 */
	@Override
	public Boolean existTask(Long circleId, Long taskId){
		return circleMapper.existTask(circleId,taskId);
	}
}

